package com.yixq.soa.service.web.auth.service;

import java.util.Calendar;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yixq.soa.service.comm.constant.Constant;
import com.yixq.soa.service.comm.redis.RedisDoorduTemplate;
import com.yixq.soa.service.web.auth.TokenManager;
import com.yixq.soa.service.web.auth.model.TokenModel;

/**
 * token redis manager
 * @ClassName: RedisTokenManager
 * @Description: 
 * @author xiaoqun.yi yixq@doordu.com  
 * @date 2017年4月6日 下午5:55:21
 * @version V1.0
 */
@Service
public class RedisTokenManager implements TokenManager {
	protected static final Logger log = LoggerFactory.getLogger(RedisTokenManager.class);
	@Autowired
	private RedisDoorduTemplate redis;

	public TokenModel createToken(String appId) {
		// 使用uuid作为源token
		String token = UUID.randomUUID().toString().replace("-", "");
		TokenModel model = new TokenModel(appId, token);
		// 存储到redis并设置过期时间
		String tokenKey = tokenKeyPrefix + appId;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, Constant.TOKEN_EXPIRES_HOUR);
		redis.set(tokenKey, token);
		redis.expireAt(tokenKey, cal.getTime());
		log.warn("******token:"+redis.get(tokenKey));
		return model;
	}

	public TokenModel getToken(String authentication) {
		if (authentication == null || authentication.length() == 0) {
			return null;
		}
		String[] param = authentication.split("_");
		if (param.length != 2) {
			return null;
		}
		// 使用appId和源token简单拼接成的token，可以增加加密措施
		String appId = param[0];
		String token = param[1];
		return new TokenModel(appId, token);
	}

	public boolean checkToken(TokenModel model) {
		if (model == null) {
			return false;
		}
		String tokenKey = tokenKeyPrefix + model.getAppId();
		String token =redis.get(tokenKey);
		if (token == null || !token.equals(model.getToken())) {
			return false;
		}
		// 如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间

	
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, Constant.TOKEN_EXPIRES_HOUR);
		redis.set(tokenKey, token);
		redis.expireAt(tokenKey, cal.getTime());

		return true;
	}

	public void deleteToken(String appId) {
		String tokenKey = tokenKeyPrefix + appId;
		redis.delete(tokenKey);
	}

	@Override
	public boolean createToken(String appId, String appSecret) {
		// 使用uuid作为源token
		String token = UUID.randomUUID().toString().replace("-", "");
		TokenModel model = new TokenModel(appId, token);
		// 存储到redis并设置过期时间
		String tokenKey = tokenKeyPrefix + appId;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, Constant.TOKEN_EXPIRES_HOUR);
		redis.set(tokenKey, token);
		redis.expireAt(tokenKey, cal.getTime());
		return true;
	}
}